// Content Script - 页面注入脚本，负责捕获用户操作

// 防止重复注入
if (window.scribeHowInjected) {
  console.log('ScribeHow: Content script already injected, skipping...');
  // 如果已经注入，直接退出
} else {
  window.scribeHowInjected = true;

class ScribeHowRecorder {
  constructor() {
    this.isRecording = false;
    this.isPaused = false; // 新增暂停状态
    this.recordingId = null;
    this.eventQueue = [];
    this.lastEventTime = 0;
    this.sidebar = null;
    this.hoverElement = null;
    this.highlightOverlay = null;
    this.inputTimeout = null;
    this.highlightColor = '#ff5252'; // 默认高亮颜色

    // 智能选择器生成器
    this.selectorGenerator = new SmartSelectorGenerator();

    // 初始化
    this.init();
  }

  async init() {
    console.log('ScribeHow: Initializing recorder...');
    
    // 加载用户设置
    await this.loadSettings();
    
    // 监听来自背景脚本的消息
    chrome.runtime.onMessage.addListener(this.handleMessage.bind(this));
    
    // 创建UI组件
    this.createHighlightOverlay();
    
    // 设置事件监听器
    this.setupEventListeners();
    
    console.log('ScribeHow: Recorder initialization complete');
  }

  handleMessage(request, sender, sendResponse) {
    switch (request.action) {
      case 'START_RECORDING':
        this.startRecording(request.recordingId);
        sendResponse({ success: true });
        break;
        
      case 'STOP_RECORDING':
        this.stopRecording();
        sendResponse({ success: true });
        break;
        
      case 'PROCESS_SCREENSHOT':
        this.processScreenshot(request.screenshot, request.highlightRect, request.sidebarWidth).then(processed => {
          sendResponse({ processedScreenshot: processed });
        });
        return true; // 保持消息通道开放，等待异步操作完成
        
      case 'UPDATE_SETTINGS':
        this.loadSettings(); // 重新加载设置
        this.updateHighlightColor(); // 更新高亮颜色
        sendResponse({ success: true });
        break;
        
      default:
        sendResponse({ success: false, error: 'Unknown action' });
    }
    
    return true;
  }

  async startRecording(recordingId) {
    console.log('🚀 ScribeHow: Starting recording with ID:', recordingId);
    
    try {
      // 重新加载设置以获取最新的高亮颜色
      await this.loadSettings();
      
      // 设置录制状态
      this.isRecording = true;
      this.recordingId = recordingId;
      
      // 强制重新创建侧边栏以确保可靠性
      if (this.sidebar) {
        this.sidebar.remove();
        this.sidebar = null;
      }
      
      // 等待一帧，确保旧的侧边栏完全移除
      await new Promise(resolve => requestAnimationFrame(resolve));
      
      // 创建新的侧边栏
      this.createSidebar();
      
      // 等待侧边栏DOM插入完成
      await new Promise(resolve => setTimeout(resolve, 100));
      
      // 显示侧边栏
      this.showSidebar();
      
      // 添加录制标识到body
      document.body.classList.add('scribehow-recording');
      
      // 更新高亮覆盖层颜色
      this.updateHighlightColor();
      
      console.log('🚀 ScribeHow: Recording state set to:', this.isRecording);
      console.log('🚀 ScribeHow: Using highlight color:', this.highlightColor);
      
      // 验证侧边栏状态
      const verification = setTimeout(() => {
        const sidebar = document.querySelector('.scribehow-sidebar');
        const stepsContainer = document.getElementById('scribehow-steps');
        
        console.log('🔍 ScribeHow: Sidebar verification:');
        console.log('  - Sidebar exists:', !!sidebar);
        console.log('  - Sidebar visible:', sidebar && sidebar.classList.contains('scribehow-sidebar-visible'));
        console.log('  - Steps container exists:', !!stepsContainer);
        
        if (!sidebar || !stepsContainer) {
          console.log('⚠️ ScribeHow: Sidebar verification failed, recreating...');
          this.createSidebar();
          this.showSidebar();
        }
        
        // 添加初始导航步骤
        this.updateSidebar({
          action: 'navigate',
          description: `Navigated to ${document.title}`,
          screenshot: false
        });
        
        console.log('✅ ScribeHow: Recording ready! Click any element to capture steps.');
      }, 500);
      
    } catch (error) {
      console.error('❌ ScribeHow: Error starting recording:', error);
      
      // 回退处理
      this.isRecording = false;
      this.recordingId = null;
    }
  }

  stopRecording() {
    console.log('🛑 ScribeHow: Stopping recording');

    this.isRecording = false;
    this.isPaused = false; // 重置暂停状态
    this.recordingId = null;
    this.hideSidebar();

    // 移除事件监听器
    this.removeEventListeners();

    // 移除录制标识
    document.body.classList.remove('scribehow-recording');

    // 清理hover效果
    this.hideHighlight();

    console.log('🛑 ScribeHow: Recording stopped and cleaned up');
  }

  // 新增暂停录制方法
  pauseRecording() {
    console.log('⏸️ ScribeHow: Pausing recording');
    this.isPaused = true;
    this.updateSidebarControls();
    this.hideHighlight(); // 暂停时隐藏高亮
    console.log('⏸️ ScribeHow: Recording paused');
  }

  // 新增继续录制方法
  resumeRecording() {
    console.log('▶️ ScribeHow: Resuming recording');
    this.isPaused = false;
    this.updateSidebarControls();
    console.log('▶️ ScribeHow: Recording resumed');
  }

  setupEventListeners() {
    console.log('ScribeHow: Setting up event listeners');
    
    // 移除可能存在的旧事件监听器
    this.removeEventListeners();
    
    // 定义事件处理函数
    this.clickHandler = (event) => {
      if (!this.isRecording || this.isPaused) return; // 添加暂停状态检查

      if (this.isOwnElement(event.target)) {
        console.log('ScribeHow: Click on own element, ignoring');
        return;
      }

      // 防抖处理
      const now = Date.now();
      if (now - this.lastEventTime < 200) {
        return;
      }
      this.lastEventTime = now;

      console.log('🔥 ScribeHow: Click detected on:', event.target.tagName, (event.target.textContent || '').substring(0, 30));
      this.handleClick(event);
    };
    
    // 绑定事件监听器
    document.addEventListener('click', this.clickHandler, true);
    
    // 其他事件监听器
    this.inputHandler = (event) => {
      if (!this.isRecording || this.isPaused || this.isOwnElement(event.target)) return; // 添加暂停状态检查
      clearTimeout(this.inputTimeout);
      this.inputTimeout = setTimeout(() => this.handleInput(event), 500);
    };

    this.changeHandler = (event) => {
      if (!this.isRecording || this.isPaused || this.isOwnElement(event.target)) return; // 添加暂停状态检查
      this.handleChange(event);
    };

    this.submitHandler = (event) => {
      if (!this.isRecording || this.isPaused || this.isOwnElement(event.target)) return; // 添加暂停状态检查
      this.handleSubmit(event);
    };
    
    this.mouseMoveHandler = this.handleMouseMove.bind(this);
    
    document.addEventListener('input', this.inputHandler, true);
    document.addEventListener('change', this.changeHandler, true);
    document.addEventListener('submit', this.submitHandler, true);
    document.addEventListener('mousemove', this.mouseMoveHandler, true);
    
    // 监听页面导航
    this.observeNavigation();
    
    console.log('ScribeHow: Event listeners setup completed');
  }
  
  removeEventListeners() {
    if (this.clickHandler) {
      document.removeEventListener('click', this.clickHandler, true);
    }
    if (this.inputHandler) {
      document.removeEventListener('input', this.inputHandler, true);
    }
    if (this.changeHandler) {
      document.removeEventListener('change', this.changeHandler, true);
    }
    if (this.submitHandler) {
      document.removeEventListener('submit', this.submitHandler, true);
    }
    if (this.mouseMoveHandler) {
      document.removeEventListener('mousemove', this.mouseMoveHandler, true);
    }
  }

  handleClick(event) {
    console.log('🔥 ScribeHow: handleClick() FIRED for', event.target.tagName);
    
    if (!this.isRecording) {
      console.log('ScribeHow: Not recording, skipping click');
      return;
    }
    
    const element = event.target;
    
    try {
      const selector = this.selectorGenerator.generate(element);
      const elementInfo = this.getElementInfo(element);
      
      console.log('🔥 ScribeHow: Processing element:', {
        tag: element.tagName,
        text: elementInfo.text,
        description: elementInfo.description
      });
      
      const stepData = {
        action: 'click',
        description: `Click on ${elementInfo.description}`,
        selector: selector,
        elementType: element.tagName.toLowerCase(),
        elementText: elementInfo.text,
        position: this.getElementPosition(element),
        url: window.location.href,
        timestamp: Date.now(),
        screenshot: true
      };
      
      console.log('🔥 ScribeHow: Step data created:', stepData);
      
      // 立即调用recordStep
      this.recordStep(stepData);
      
    } catch (error) {
      console.error('❌ ScribeHow: Error in handleClick:', error);
      console.error('❌ Stack trace:', error.stack);
    }
  }

  handleDoubleClick(event) {
    const element = event.target;
    const selector = this.selectorGenerator.generate(element);
    const elementInfo = this.getElementInfo(element);
    
    this.recordStep({
      action: 'double-click',
      description: `Double-click on ${elementInfo.description}`,
      selector: selector,
      elementType: element.tagName.toLowerCase(),
      elementText: elementInfo.text,
      position: this.getElementPosition(element),
      url: window.location.href,
      screenshot: true
    });
  }

  handleInput(event) {
    const element = event.target;
    const selector = this.selectorGenerator.generate(element);
    const elementInfo = this.getElementInfo(element);
    
    // 对敏感信息进行处理
    const value = this.sanitizeValue(element);
    
    this.recordStep({
      action: 'type',
      description: `Type "${value}" in ${elementInfo.description}`,
      selector: selector,
      elementType: element.tagName.toLowerCase(),
      inputType: element.type || 'text',
      value: value,
      position: this.getElementPosition(element),
      url: window.location.href,
      screenshot: true
    });
  }

  handleChange(event) {
    const element = event.target;
    const selector = this.selectorGenerator.generate(element);
    const elementInfo = this.getElementInfo(element);
    
    if (element.tagName === 'SELECT') {
      const selectedOption = element.options[element.selectedIndex];
      this.recordStep({
        action: 'select',
        description: `Select "${selectedOption.text}" from ${elementInfo.description}`,
        selector: selector,
        value: element.value,
        text: selectedOption.text,
        position: this.getElementPosition(element),
        url: window.location.href,
        screenshot: true
      });
    } else if (element.type === 'checkbox' || element.type === 'radio') {
      this.recordStep({
        action: element.checked ? 'check' : 'uncheck',
        description: `${element.checked ? 'Check' : 'Uncheck'} ${elementInfo.description}`,
        selector: selector,
        elementType: element.type,
        checked: element.checked,
        position: this.getElementPosition(element),
        url: window.location.href,
        screenshot: true
      });
    }
  }

  handleSubmit(event) {
    const form = event.target;
    const selector = this.selectorGenerator.generate(form);
    
    this.recordStep({
      action: 'submit',
      description: `Submit form`,
      selector: selector,
      formAction: form.action,
      formMethod: form.method,
      url: window.location.href,
      screenshot: true
    });
  }



  handleMouseMove(event) {
    if (!this.isRecording || this.isPaused) return; // 添加暂停状态检查

    const element = event.target;
    if (this.isOwnElement(element)) return;

    // 高亮显示悬停元素
    if (element !== this.hoverElement) {
      this.hoverElement = element;
      this.highlightElement(element);
    }
  }

  async recordStep(stepData) {
    console.log('📝 ScribeHow: recordStep() called for action:', stepData.action);
    
    if (!this.isRecording) {
      console.log('ScribeHow: Not recording, ignoring step');
      return;
    }
    
    // 立即更新侧边栏显示（不等待截图）
    console.log('📝 ScribeHow: Immediately updating sidebar with:', stepData.description);
    this.updateSidebar(stepData);
    
    // 如果需要截图，先捕获
    if (stepData.screenshot) {
      const rect = stepData.position;
      
      console.log('📸 ScribeHow: Starting screenshot capture process');
      
      // 暂时隐藏高亮
      this.hideHighlight();
      
      // 获取侧边栏宽度用于截图裁剪（增加安全边距确保完全去除侧边栏）
      const sidebarWidth = this.sidebar && this.sidebar.classList.contains('scribehow-sidebar-visible')
        ? this.sidebar.offsetWidth + 40  // 侧边栏宽度 + 40px安全边距，确保完全裁剪
        : 0;
      
      console.log('ScribeHow: Sidebar width for cropping:', sidebarWidth, 'offsetWidth:', this.sidebar && this.sidebar.offsetWidth);
      
      // 等待一帧确保UI更新
      await new Promise(resolve => requestAnimationFrame(resolve));
      
      // 请求背景脚本捕获截图
      try {
        chrome.runtime.sendMessage({
          action: 'CAPTURE_SCREENSHOT',
          highlightRect: rect,
          sidebarWidth: sidebarWidth
        }, (response) => {
          if (chrome.runtime.lastError) {
            console.log('ScribeHow: Screenshot capture error:', chrome.runtime.lastError);
            return;
          }
        console.log('📸 ScribeHow: Screenshot capture response received');
        console.log('📸 ScribeHow: Response object:', response);
        
        if (response && response.success && response.screenshot) {
          stepData.screenshot = response.screenshot;
          console.log('📸 ScribeHow: Screenshot data attached to step');
        } else {
          console.error('❌ ScribeHow: Screenshot capture failed or invalid response');
          console.error('❌ ScribeHow: Response details:', {
            hasResponse: !!response,
            success: response && response.success,
            hasScreenshot: response && !!response.screenshot,
            screenshotLength: response && response.screenshot && response.screenshot.length
          });
        }
        
        // 发送步骤到背景脚本
        try {
          chrome.runtime.sendMessage({
            action: 'ADD_STEP',
            step: stepData
          }, (addResponse) => {
            if (chrome.runtime.lastError) {
              console.log('ScribeHow: Runtime error:', chrome.runtime.lastError);
            } else {
              console.log('ScribeHow: Add step response:', addResponse);
            }
          });
        } catch (error) {
          console.log('ScribeHow: Failed to send message:', error);
        }
        
        // 截图完成后更新已显示的步骤
        console.log('📸 ScribeHow: Processing screenshot response');
        console.log('📸 ScribeHow: Response success:', response && response.success);
        console.log('📸 ScribeHow: Has screenshot:', response && response.success && !!response.screenshot);
        
        if (response && response.success && response.screenshot) {
          console.log('✅ ScribeHow: Valid screenshot received, updating UI');
          
          // 找到最新的步骤元素
          setTimeout(() => {
            const stepElements = document.querySelectorAll('.scribehow-step');
            const latestStep = stepElements[stepElements.length - 1];
            
            console.log('📸 ScribeHow: Found', stepElements.length, 'steps, updating latest step');
            
            if (latestStep) {
              // 移除加载指示器
              const loadingDiv = latestStep.querySelector('.scribehow-step-loading');
              if (loadingDiv) {
                loadingDiv.remove();
                console.log('📸 ScribeHow: Loading indicator removed');
              }
              
              // 添加截图，即使已经存在也要更新
              let screenshotDiv = latestStep.querySelector('.scribehow-step-screenshot');
              if (!screenshotDiv) {
                screenshotDiv = document.createElement('div');
                screenshotDiv.className = 'scribehow-step-screenshot';
                latestStep.appendChild(screenshotDiv);
              }
              
              // 设置截图内容
              screenshotDiv.innerHTML = `<img src="${response.screenshot}" alt="Step screenshot" loading="eager" class="screenshot-preview">`;
              
              console.log('✅ ScribeHow: Screenshot image added to DOM');
              
              // 绑定预览事件
              const img = screenshotDiv.querySelector('img');
              if (img) {
                // 检查图片是否加载成功
                img.onload = () => {
                  console.log('✅ ScribeHow: Screenshot image loaded successfully');
                };
                img.onerror = (error) => {
                  console.error('❌ ScribeHow: Screenshot image failed to load');
                  console.error('❌ ScribeHow: Image src length:', img.src.length);
                  console.error('❌ ScribeHow: Image src start:', img.src.substring(0, 100));
                  
                  // 替换为错误占位符
                  img.src = '';
                };
                
                img.addEventListener('click', (e) => {
                  console.log('ScribeHow: Screenshot clicked for preview');
                  window.scribeHowPreviewImage(e.target.src);
                });
              }
            } else {
              console.error('❌ ScribeHow: No steps found to update with screenshot');
            }
          }, 100); // 稍微延迟确保DOM更新完成
        } else {
          console.error('❌ ScribeHow: Invalid screenshot response:', response);
        }
        });
      } catch (error) {
        console.log('ScribeHow: Failed to request screenshot:', error);
      }
    } else {
      console.log('ScribeHow: Adding step without screenshot');
      
      // 不需要截图的步骤直接发送
      try {
        chrome.runtime.sendMessage({
          action: 'ADD_STEP',
          step: stepData
        }, (response) => {
          if (chrome.runtime.lastError) {
            console.log('ScribeHow: Runtime error:', chrome.runtime.lastError);
          } else {
            console.log('ScribeHow: Add step (no screenshot) response:', response);
          }
        });
      } catch (error) {
        console.log('ScribeHow: Failed to send message:', error);
      }
    }
  }

  // UI相关方法
  createHighlightOverlay() {
    this.highlightOverlay = document.createElement('div');
    this.highlightOverlay.className = 'scribehow-highlight-overlay';
    this.highlightOverlay.style.cssText = `
      position: absolute;
      pointer-events: none;
      z-index: 999999;
      display: none;
      transition: all 0.2s ease;
      border-radius: 4px;
    `;
    document.body.appendChild(this.highlightOverlay);
  }

  createSidebar() {
    console.log('📦 ScribeHow: Creating sidebar');
    
    // 移除任何现有的侧边栏
    const existingSidebars = document.querySelectorAll('.scribehow-sidebar');
    existingSidebars.forEach(sidebar => {
      console.log('ScribeHow: Removing existing sidebar');
      sidebar.remove();
    });
    
    this.sidebar = null;
    
    // 创建侧边栏容器
    this.sidebar = document.createElement('div');
    this.sidebar.className = 'scribehow-sidebar';
    this.sidebar.innerHTML = `
      <div class="scribehow-sidebar-header">
        <h3>ScribeHow</h3>
        <div class="scribehow-recording-indicator">
          <span class="scribehow-recording-dot"></span>
          Recording Steps
        </div>
      </div>
      <div class="scribehow-steps-container" id="scribehow-steps">
        <div class="empty-state">
          <div class="empty-icon">
            <svg width="48" height="48" viewBox="0 0 48 48" fill="none" stroke="currentColor">
              <circle cx="24" cy="24" r="10" stroke-width="2"/>
              <circle cx="24" cy="24" r="3" fill="currentColor"/>
            </svg>
          </div>
          <p class="empty-text">Recording in progress</p>
          <p class="empty-subtext">Perform actions to capture steps</p>
        </div>
      </div>
      <div class="scribehow-sidebar-footer">
        <div class="scribehow-controls">
          <button class="scribehow-btn scribehow-btn-pause" id="scribehow-pause">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <rect x="6" y="4" width="4" height="16" rx="1"/>
              <rect x="14" y="4" width="4" height="16" rx="1"/>
            </svg>
            Pause
          </button>
          <button class="scribehow-btn scribehow-btn-stop" id="scribehow-stop">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <rect x="6" y="6" width="12" height="12" rx="2"/>
            </svg>
            Stop
          </button>
        </div>
      </div>
    `;
    
    // 确保body存在
    if (!document.body) {
      console.error('❌ ScribeHow: Document body not available');
      return;
    }
    
    document.body.appendChild(this.sidebar);
    
    console.log('📦 ScribeHow: Sidebar HTML created and added to body');
    
    // 验证DOM插入成功
    const insertedSidebar = document.querySelector('.scribehow-sidebar');
    const insertedContainer = document.getElementById('scribehow-steps');
    
    if (!insertedSidebar || !insertedContainer) {
      console.error('❌ ScribeHow: Sidebar DOM insertion failed');
      return;
    }
    
    console.log('✅ ScribeHow: Sidebar DOM insertion verified');
    
    // 绑定控制按钮事件
    const pauseBtn = document.getElementById('scribehow-pause');
    const stopBtn = document.getElementById('scribehow-stop');

    if (pauseBtn) {
      pauseBtn.addEventListener('click', () => {
        console.log('ScribeHow: Pause/Resume button clicked');
        if (this.isPaused) {
          this.resumeRecording();
        } else {
          this.pauseRecording();
        }
      });
      console.log('ScribeHow: Pause button event bound');
    } else {
      console.log('❌ ScribeHow: Pause button not found');
    }

    if (stopBtn) {
      stopBtn.addEventListener('click', () => {
        console.log('ScribeHow: Stop button clicked');
        try {
          chrome.runtime.sendMessage({ action: 'STOP_RECORDING' }, (response) => {
            if (chrome.runtime.lastError) {
              console.log('ScribeHow: Runtime error on stop:', chrome.runtime.lastError);
            }
          });
        } catch (error) {
          console.log('ScribeHow: Failed to send stop message:', error);
        }
      });
      console.log('ScribeHow: Stop button event bound');
    } else {
      console.log('❌ ScribeHow: Stop button not found');
    }
    
    console.log('✅ ScribeHow: Sidebar creation completed');
  }

  // 新增方法：更新侧边栏控制按钮状态
  updateSidebarControls() {
    const pauseBtn = document.getElementById('scribehow-pause');
    const recordingIndicator = document.querySelector('.scribehow-recording-indicator');

    if (pauseBtn) {
      if (this.isPaused) {
        // 暂停状态：显示继续按钮
        pauseBtn.innerHTML = `
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <polygon points="8,5 19,12 8,19"/>
          </svg>
          Resume
        `;
        pauseBtn.classList.add('scribehow-btn-resume');
        pauseBtn.classList.remove('scribehow-btn-pause');
      } else {
        // 录制状态：显示暂停按钮
        pauseBtn.innerHTML = `
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <rect x="6" y="4" width="4" height="16" rx="1"/>
            <rect x="14" y="4" width="4" height="16" rx="1"/>
          </svg>
          Pause
        `;
        pauseBtn.classList.add('scribehow-btn-pause');
        pauseBtn.classList.remove('scribehow-btn-resume');
      }
    }

    // 更新录制指示器
    if (recordingIndicator) {
      const indicatorText = recordingIndicator.querySelector('span:last-child') || recordingIndicator;
      if (this.isPaused) {
        indicatorText.textContent = 'Recording Paused';
        recordingIndicator.classList.add('paused');
      } else {
        indicatorText.textContent = 'Recording Steps';
        recordingIndicator.classList.remove('paused');
      }
    }
  }

  showSidebar() {
    console.log('👁️ ScribeHow: showSidebar() called');
    
    if (!this.sidebar) {
      console.log('ScribeHow: Sidebar not found, creating it');
      this.createSidebar();
      
      // 等待DOM插入
      setTimeout(() => {
        if (this.sidebar) {
          this.sidebar.classList.add('scribehow-sidebar-visible');
          document.body.classList.add('scribehow-body-shifted');
        }
      }, 50);
    } else {
      this.sidebar.classList.add('scribehow-sidebar-visible');
      document.body.classList.add('scribehow-body-shifted');
    }
    
    // 验证显示状态
    setTimeout(() => {
      const isVisible = this.sidebar && this.sidebar.classList.contains('scribehow-sidebar-visible');
      console.log('👁️ ScribeHow: Sidebar visibility verified:', isVisible);
      
              if (!isVisible) {
        console.log('⚠️ ScribeHow: Sidebar not visible, forcing display...');
        // 强制显示 - 紧贴右边缘
        if (this.sidebar) {
          this.sidebar.style.right = '0px';
          this.sidebar.style.visibility = 'visible';
          this.sidebar.style.opacity = '1';
        }
      }
    }, 200);
  }

  hideSidebar() {
    if (this.sidebar) {
      this.sidebar.classList.remove('scribehow-sidebar-visible');
      document.body.classList.remove('scribehow-body-shifted');
      
      // 清空步骤列表
      const stepsContainer = document.getElementById('scribehow-steps');
      if (stepsContainer) {
        stepsContainer.innerHTML = '';
      }
    }
  }

  updateSidebar(step) {
    console.log('📝 ScribeHow: updateSidebar called for:', step.action);
    
    // 多重检查确保侧边栏存在
    let stepsContainer = document.getElementById('scribehow-steps');
    let retryCount = 0;
    
    while (!stepsContainer && retryCount < 3) {
      console.log(`ScribeHow: Steps container not found, attempt ${retryCount + 1}/3`);
      
      // 强制重新创建侧边栏
      if (this.sidebar) {
        this.sidebar.remove();
      }
      
      this.createSidebar();
      this.showSidebar();
      
      stepsContainer = document.getElementById('scribehow-steps');
      retryCount++;
      
      if (!stepsContainer && retryCount < 3) {
        console.log('ScribeHow: Retrying after delay...');
        // 同步等待，因为这是关键路径
        const start = Date.now();
        while (Date.now() - start < 100) {
          // 短暂等待
        }
      }
    }
    
    if (!stepsContainer) {
      console.error('❌ ScribeHow: Failed to create steps container after 3 attempts');
      return;
    }
    
    console.log('✅ ScribeHow: Steps container verified');
    
    // 如果是第一个步骤，清除空状态
    const emptyState = stepsContainer.querySelector('.empty-state');
    if (emptyState) {
      console.log('ScribeHow: Removing empty state');
      emptyState.remove();
    }
    
    const stepElement = document.createElement('div');
    stepElement.className = 'scribehow-step';
    stepElement.innerHTML = `
      <div class="scribehow-step-header">
        <div class="scribehow-step-number">${stepsContainer.children.length + 1}</div>
        <div class="scribehow-step-content">
          <div class="scribehow-step-action">${step.action}</div>
          <div class="scribehow-step-description">${step.description}</div>
          <div class="scribehow-step-meta">
            <span class="scribehow-step-time">${new Date().toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})}</span>
          </div>
        </div>
      </div>
      ${step.screenshot ? `<div class="scribehow-step-screenshot"><img src="${step.screenshot}" alt="Step screenshot" loading="eager" class="screenshot-preview"></div>` : '<div class="scribehow-step-loading">📸 Capturing screenshot...</div>'}
    `;
    
    // 移除其他步骤的latest类
    stepsContainer.querySelectorAll('.scribehow-step.latest').forEach(el => {
      el.classList.remove('latest');
    });
    
    // 为新步骤添加latest类并设置颜色
    stepElement.classList.add('latest');
    
    // 设置新步骤的高亮颜色
    const beforeElement = stepElement;
    if (beforeElement) {
      const rgba = this.hexToRgba(this.highlightColor, 0.15);
      beforeElement.style.setProperty('--highlight-color', this.highlightColor);
      beforeElement.style.setProperty('--highlight-bg', rgba);
    }
    
    stepsContainer.appendChild(stepElement);
    
    console.log('✅ ScribeHow: Step successfully added to sidebar');
    console.log('ScribeHow: Total steps now:', stepsContainer.children.length);
    console.log('ScribeHow: Step has screenshot?', !!step.screenshot);
    
    // 如果步骤有截图，验证图片元素
    if (step.screenshot) {
      const img = stepElement.querySelector('img.screenshot-preview');
      if (img) {
        console.log('📸 ScribeHow: Screenshot img element created');
        img.onload = () => console.log('✅ ScribeHow: Screenshot loaded successfully');
        img.onerror = () => console.error('❌ ScribeHow: Screenshot failed to load');
      }
    }
    
    // 多重检查确保侧边栏可见
    const isCurrentlyVisible = this.sidebar && this.sidebar.classList.contains('scribehow-sidebar-visible');
    
    if (!isCurrentlyVisible) {
      console.log('ScribeHow: Sidebar not visible, forcing show');
      this.showSidebar();
    }
    
    // 额外验证：检查侧边栏是否在视口中
    setTimeout(() => {
      if (this.sidebar) {
        const rect = this.sidebar.getBoundingClientRect();
        const isInViewport = rect.right > 0 && rect.left < window.innerWidth;
        
        if (!isInViewport) {
          console.log('⚠️ ScribeHow: Sidebar not in viewport, forcing position');
          this.sidebar.style.right = '0px';
          this.sidebar.style.transform = 'translateX(0)';
        }
      }
    }, 300);
    
    // 滚动到最新步骤
    stepElement.scrollIntoView({ behavior: 'smooth', block: 'end' });
    
    // 3秒后移除latest样式
    setTimeout(() => {
      stepElement.classList.remove('latest');
    }, 3000);
    
    // 为新添加的截图绑定预览事件
    const newImg = stepElement.querySelector('img.screenshot-preview');
    if (newImg) {
      newImg.addEventListener('click', (e) => {
        const src = e.target.src;
        if (src) {
          window.scribeHowPreviewImage(src);
        }
      });
    }
    
    console.log('✅ ScribeHow: Sidebar update completed successfully');
    
    // 确保侧边栏滚动到最新步骤
    setTimeout(() => {
      if (stepsContainer && stepsContainer.children.length > 0) {
        const lastStep = stepsContainer.children[stepsContainer.children.length - 1];
        lastStep.scrollIntoView({ behavior: 'smooth', block: 'end' });
      }
    }, 100);
  }

  highlightElement(element) {
    if (!element || !this.highlightOverlay) return;
    
    const rect = element.getBoundingClientRect();
    
    this.highlightOverlay.style.left = `${rect.left + window.scrollX}px`;
    this.highlightOverlay.style.top = `${rect.top + window.scrollY}px`;
    this.highlightOverlay.style.width = `${rect.width}px`;
    this.highlightOverlay.style.height = `${rect.height}px`;
    this.highlightOverlay.style.display = 'block';
  }

  hideHighlight() {
    if (this.highlightOverlay) {
      this.highlightOverlay.style.display = 'none';
    }
  }

  // 辅助方法
  getElementInfo(element) {
    let description = element.tagName.toLowerCase();
    let text = '';
    
    // 获取元素的描述文本
    if (element.textContent) {
      text = element.textContent.trim().substring(0, 50);
    }
    
    // 根据元素类型生成描述
    if (element.tagName === 'BUTTON') {
      description = `button "${text || 'unnamed'}"`;
    } else if (element.tagName === 'A') {
      description = `link "${text || element.href}"`;
    } else if (element.tagName === 'INPUT') {
      const type = element.type || 'text';
      const label = this.findLabelForElement(element);
      description = `${type} field "${label || element.placeholder || element.name || 'unnamed'}"`;
    } else if (element.tagName === 'SELECT') {
      const label = this.findLabelForElement(element);
      description = `dropdown "${label || element.name || 'unnamed'}"`;
    } else if (text) {
      description = `"${text}"`;
    }
    
    return { description, text };
  }

  findLabelForElement(element) {
    // 通过for属性查找label
    if (element.id) {
      const label = document.querySelector(`label[for="${element.id}"]`);
      if (label) return label.textContent.trim();
    }
    
    // 查找父级label
    const parentLabel = element.closest('label');
    if (parentLabel) {
      return parentLabel.textContent.trim();
    }
    
    // 查找相邻的label
    const prevElement = element.previousElementSibling;
    if (prevElement && prevElement.tagName === 'LABEL') {
      return prevElement.textContent.trim();
    }
    
    return null;
  }

  getElementPosition(element) {
    const rect = element.getBoundingClientRect();
    return {
      x: rect.left,
      y: rect.top,
      width: rect.width,
      height: rect.height
    };
  }

  sanitizeValue(element) {
    const sensitiveTypes = ['password', 'tel', 'email'];
    
    if (sensitiveTypes.includes(element.type)) {
      return '•'.repeat(element.value.length);
    }
    
    return element.value;
  }



  isOwnElement(element) {
    // 检查是否是插件自己的UI元素
    if (!element) return true;
    
    // 检查是否有closest方法
    if (!element.closest || typeof element.closest !== 'function') {
      // 回退检查：检查className和id
      const className = element.className;
      const id = element.id;
      
      if (className && (className.includes('scribehow') || className.includes('recorder'))) {
        return true;
      }
      if (id && (id.includes('scribehow') || id.includes('recorder'))) {
        return true;
      }
      return false;
    }
    
    // 检查是否在插件UI内
    const isInSidebar = element.closest('.scribehow-sidebar');
    const isInOverlay = element.closest('.scribehow-highlight-overlay'); 
    
    if (isInSidebar || isInOverlay) {
      console.log('ScribeHow: Element is part of plugin UI');
      return true;
    }
    
    return false;
  }

  async loadSettings() {
    try {
      const result = await chrome.storage.local.get('scribehow_settings');
      const settings = result.scribehow_settings || {};
      
      // 设置高亮颜色，默认为红色
      this.highlightColor = settings.highlightColor || '#ff5252';
      
      console.log('ScribeHow: Loaded settings, highlight color:', this.highlightColor);
    } catch (error) {
      console.log('ScribeHow: Failed to load settings, using default color');
      this.highlightColor = '#ff5252';
    }
  }
  
  updateHighlightColor() {
    if (this.highlightOverlay) {
      // 将hex颜色转换为rgba
      const rgba = this.hexToRgba(this.highlightColor, 0.08);
      
      this.highlightOverlay.style.borderColor = this.highlightColor;
      this.highlightOverlay.style.backgroundColor = rgba;
      this.highlightOverlay.style.boxShadow = `0 4px 12px ${this.hexToRgba(this.highlightColor, 0.3)}`;
    }
  }
  
  hexToRgba(hex, alpha) {
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
  }

  observeNavigation() {
    // 监听History API
    const originalPushState = history.pushState;
    const originalReplaceState = history.replaceState;
    
    history.pushState = (...args) => {
      originalPushState.apply(history, args);
      this.handleNavigation();
    };
    
    history.replaceState = (...args) => {
      originalReplaceState.apply(history, args);
      this.handleNavigation();
    };
    
    // 监听popstate事件
    window.addEventListener('popstate', () => {
      this.handleNavigation();
    });
  }

  handleNavigation() {
    if (!this.isRecording) return;
    
    this.recordStep({
      action: 'navigate',
      description: `Navigated to ${document.title}`,
      url: window.location.href,
      pageTitle: document.title
    });
  }

  processScreenshot(screenshot, highlightRect, sidebarWidth = 0) {
    // 在canvas上处理截图，添加高亮框并裁剪侧边栏
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const img = new Image();

    return new Promise((resolve) => {
      img.onload = () => {
        // 改进的裁剪算法，确保完全去除侧边栏
        let cropWidth = 0;
        if (sidebarWidth > 0) {
          // 使用简化但更可靠的计算方式
          const scaleFactor = img.width / window.innerWidth;
          cropWidth = Math.ceil(sidebarWidth * scaleFactor);

          // 额外增加安全边距，确保完全去除侧边栏内容
          cropWidth += Math.ceil(30 * scaleFactor); // 30px安全边距

          console.log('ScribeHow: Crop calculation - sidebarWidth:', sidebarWidth, 'scaleFactor:', scaleFactor, 'cropWidth:', cropWidth, 'imgWidth:', img.width, 'windowWidth:', window.innerWidth);
        }

        // 确保裁剪后的宽度合理
        const finalWidth = Math.max(100, Math.min(img.width - cropWidth, img.width));

        console.log('ScribeHow: Final dimensions - width:', finalWidth, 'height:', img.height, 'original width:', img.width);

        // 设置canvas尺寸为裁剪后的尺寸
        canvas.width = finalWidth;
        canvas.height = img.height;

        // 绘制裁剪后的截图（去除右侧侧边栏区域）
        try {
          ctx.drawImage(
            img,
            0, 0, finalWidth, img.height,  // 源区域（裁剪掉右侧）
            0, 0, finalWidth, img.height   // 目标区域
          );

          // 不在截图上绘制高亮框，保持截图的原始干净状态

          const result = canvas.toDataURL('image/png');
          console.log('ScribeHow: Screenshot processed successfully, data URL length:', result.length);
          resolve(result);
        } catch (error) {
          console.error('ScribeHow: Error processing screenshot:', error);
          // 如果处理失败，返回原始截图
          resolve(screenshot);
        }
      };

      img.onerror = (error) => {
        console.error('ScribeHow: Failed to load screenshot image:', error);
        resolve(screenshot); // 返回原始截图
      };

      img.src = screenshot;
    });
  }
}

// 智能选择器生成器
class SmartSelectorGenerator {
  generate(element) {
    // 策略1: ID选择器
    if (element.id) {
      return `#${this.escapeSelector(element.id)}`;
    }
    
    // 策略2: 特定属性选择器
    const attributes = ['data-testid', 'data-test-id', 'data-cy', 'aria-label'];
    for (const attr of attributes) {
      const value = element.getAttribute(attr);
      if (value) {
        return `[${attr}="${this.escapeSelector(value)}"]`;
      }
    }
    
    // 策略3: 唯一类名组合
    const uniqueSelector = this.generateUniqueClassSelector(element);
    if (uniqueSelector) {
      return uniqueSelector;
    }
    
    // 策略4: 层级路径
    return this.generatePathSelector(element);
  }
  
  generateUniqueClassSelector(element) {
    if (!element.className) return null;
    
    const classes = Array.from(element.classList).filter(cls => !cls.startsWith('scribehow-'));
    if (classes.length === 0) return null;
    
    // 尝试不同的类名组合
    for (let i = 1; i <= classes.length; i++) {
      for (const combination of this.getCombinations(classes, i)) {
        const selector = '.' + combination.join('.');
        if (document.querySelectorAll(selector).length === 1) {
          return selector;
        }
      }
    }
    
    return null;
  }
  
  generatePathSelector(element) {
    const path = [];
    let current = element;
    
    while (current && current !== document.body) {
      let selector = current.tagName.toLowerCase();
      
      // 添加类名
      if (current.className) {
        const classes = Array.from(current.classList)
          .filter(cls => !cls.startsWith('scribehow-'))
          .slice(0, 2); // 最多使用2个类名
        
        if (classes.length > 0) {
          selector += '.' + classes.join('.');
        }
      }
      
      // 添加索引（如果有兄弟元素）
      const siblings = Array.from(current.parentElement?.children || [])
        .filter(el => el.tagName === current.tagName);
      
      if (siblings.length > 1) {
        const index = siblings.indexOf(current);
        selector += `:nth-of-type(${index + 1})`;
      }
      
      path.unshift(selector);
      
      // 最多向上查找3层
      if (path.length >= 3) break;
      
      current = current.parentElement;
    }
    
    return path.join(' > ');
  }
  
  escapeSelector(str) {
    return str.replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g, '\\$&');
  }
  
  getCombinations(arr, k) {
    const combinations = [];
    
    function backtrack(start, current) {
      if (current.length === k) {
        combinations.push([...current]);
        return;
      }
      
      for (let i = start; i < arr.length; i++) {
        current.push(arr[i]);
        backtrack(i + 1, current);
        current.pop();
      }
    }
    
    backtrack(0, []);
    return combinations;
  }
}

// 初始化录制器 - 确保DOM完全加载和扩展准备就绪
let recorder;

function initializeRecorder() {
  console.log('ScribeHow: Initializing recorder...');
  
  // 防止重复初始化
  if (recorder) {
    console.log('ScribeHow: Recorder already exists');
    return;
  }
  
  try {
    recorder = new ScribeHowRecorder();
    console.log('✅ ScribeHow: Recorder created successfully');
    
    // 添加到全局作用域以便调试
    window.scribeHowRecorder = recorder;
  } catch (error) {
    console.error('❌ ScribeHow: Failed to create recorder:', error);
    
    // 重试机制
    setTimeout(() => {
      console.log('ScribeHow: Retrying recorder creation...');
      recorder = null;
      initializeRecorder();
    }, 1000);
  }
}

// 多种初始化策略
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initializeRecorder);
} else if (document.readyState === 'interactive') {
  // DOM加载完成但资源可能还在加载
  setTimeout(initializeRecorder, 100);
} else {
  // 完全加载
  initializeRecorder();
}

// 全局图片预览功能
window.scribeHowPreviewImage = function(imageSrc) {
  // 创建预览模态框
  let modal = document.getElementById('scribehow-image-preview');
  if (!modal) {
    modal = document.createElement('div');
    modal.id = 'scribehow-image-preview';
    modal.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.9);
      z-index: 9999999;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;
      backdrop-filter: blur(4px);
    `;
    
    const content = document.createElement('div');
    content.style.cssText = `
      max-width: 90vw;
      max-height: 90vh;
      position: relative;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
    `;
    
    const img = document.createElement('img');
    img.style.cssText = `
      width: 100%;
      height: auto;
      display: block;
      object-fit: contain;
    `;
    
    const closeBtn = document.createElement('button');
    closeBtn.innerHTML = '&times;';
    closeBtn.style.cssText = `
      position: absolute;
      top: 16px;
      right: 16px;
      width: 40px;
      height: 40px;
      background: rgba(0, 0, 0, 0.7);
      color: white;
      border: none;
      border-radius: 50%;
      font-size: 20px;
      cursor: pointer;
      transition: all 0.2s ease;
    `;
    
    closeBtn.addEventListener('click', () => {
      modal.remove();
      document.body.style.overflow = '';
    });
    
    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        modal.remove();
        document.body.style.overflow = '';
      }
    });
    
    content.appendChild(img);
    content.appendChild(closeBtn);
    modal.appendChild(content);
    document.body.appendChild(modal);
    
    // ESC键关闭
    const escHandler = (e) => {
      if (e.key === 'Escape') {
        modal.remove();
        document.body.style.overflow = '';
        document.removeEventListener('keydown', escHandler);
      }
    };
    document.addEventListener('keydown', escHandler);
  }
  
  // 设置图片源
  modal.querySelector('img').src = imageSrc;
  document.body.style.overflow = 'hidden';
};

} // 结束防止重复注入的检查
